package com.dmgis.qxfw.dataservice.businessservice.yyly.controller;


import com.dmgis.entity.DmMapRectangle;
import com.dmgis.entity.DmMapPoint;
import com.dmgis.qxfw.dataservice.businessservice.api.domain.DbConfig;
import com.dmgis.qxfw.dataservice.businessservice.api.entity.qx.*;
import com.dmgis.qxfw.dataservice.businessservice.api.entity.yj.village;
import com.dmgis.qxfw.dataservice.businessservice.api.entity.zy.base_product;
import com.dmgis.qxfw.dataservice.businessservice.api.entity.zy.hxyj_warning;
import com.dmgis.qxfw.dataservice.businessservice.common.domain.*;
import com.dmgis.qxfw.dataservice.businessservice.common.domain.Warning;
import com.dmgis.qxfw.dataservice.businessservice.common.entity.*;
import com.dmgis.qxfw.dataservice.businessservice.common.service.IConfigService;
import com.dmgis.qxfw.dataservice.businessservice.common.util.*;
import com.dmgis.qxfw.dataservice.businessservice.dmgis_mongodb_srv.dataservice.service.Impl.FileRequestService;
import com.dmgis.qxfw.dataservice.businessservice.dmgis_mongodb_srv.dataservice.service.Impl.MongoService1;
import com.dmgis.qxfw.dataservice.businessservice.qxinfo.service.IQxInfoService;
import com.dmgis.qxfw.dataservice.businessservice.yyly.service.IForestryfcstService;
import com.dmgis.qxfw.dataservice.gisservice.service.ITransformService;
import com.dmgis.weblib.MapCommon;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/*气象信息预报*/
@Controller
@RequestMapping("/xtly")
public class ForestryfcstController {
    private final String operatingSystem;

    @Autowired
    public ForestryfcstController(String operatingSystem) {
        this.operatingSystem = operatingSystem;
    }

    @Resource
    private IForestryfcstService forestryfcstService;
    @Resource
    private IConfigService configService;
    @Resource
    private IQxInfoService qxInfoService;

    @Resource
    private ITransformService transformService;

    // MongoService1 ms = new MongoService1();
    FileRequestService ms = new FileRequestService();

    /* 初始化风云三号云图界面 */
    @RequestMapping("/initSatellitePage")
    @ResponseBody
    public Object initSatellitePage() {
        ArrayList<Object> arrayList = new ArrayList<Object>();/* object各种类型数据 */
        satellitenephoram3 newestDate = forestryfcstService.getCloudNewDate();
        // 加载列表
        DateTime datechar = new DateTime(newestDate.getDatechar());// DateTime类型
        String startDate = datechar.AddDays(-1).toDateString();// 开始时间
        String endDate = datechar.toDateString();// 结束时间
        arrayList.add(startDate);// 开始时间
        arrayList.add(endDate);// 结束时间
        return arrayList;
    }

    /* 获得风云三号云图 */
    @RequestMapping("/getCloud")
    @ResponseBody
    public Object getCloud(HttpServletRequest request, Model model) throws Exception {
        System.out.println(request.getParameter("startDate") + ":00:00");
        System.out.println(request.getParameter("endDate") + ":00:00");
        System.out.println(request.getSession().getServletContext().getRealPath("/") + "Temp\\FY3H\\");


        CloudSearch selectKey = new CloudSearch();// 查询类
        String startDate = request.getParameter("startDate") + ":00:00";// 开始时间
        String endDate = request.getParameter("endDate") + ":00:00";// 结束时间
        selectKey.setStartDate(startDate);
        selectKey.setEndDate(endDate);

        List<SatelliteYT> resultList = forestryfcstService.getCloud(selectKey); // 雷达结果
        String urlpath;
        if (operatingSystem.equals("Windows")) {
            urlpath = request.getSession().getServletContext().getRealPath("/") + "Temp\\FY3H\\";// 临时文件目录
        } else {
            urlpath = request.getSession().getServletContext().getRealPath("/") + "Temp/FY3H/";// 临时文件目录
        }

        FileUtil.mkDirs(urlpath);// 创建文件夹，生成多级目录
        FileUtil.ClearTempFiles(urlpath, 1000);// 清除缓存
        for (SatelliteYT satelliteNephoram : resultList) {
            System.out.println(satelliteNephoram.getFxmin());
            if(satelliteNephoram.getFxmin()==null||satelliteNephoram.getFxmax()==null
                    || satelliteNephoram.getFymin()==null||satelliteNephoram.getFymax()==null){
                System.out.println("null");
                break;
            }
            DmMapPoint dmDot = new DmMapPoint(satelliteNephoram.getFxmin(), satelliteNephoram.getFymin());
            DmMapPoint dmDot1 = new DmMapPoint(satelliteNephoram.getFxmax(), satelliteNephoram.getFymax());
            DmMapPoint ltDot = transformService.LambertConvertToLonLat(dmDot.x, dmDot.y);
            DmMapPoint ltDot1 = transformService.LambertConvertToLonLat(dmDot1.x, dmDot1.y);
            satelliteNephoram.setFymin(ltDot.y);
            satelliteNephoram.setFxmin(ltDot.x);
            satelliteNephoram.setFymax(ltDot1.y);
            satelliteNephoram.setFxmax(ltDot1.x);
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            String fileName = DbConfig.getYt3AFileName(satelliteNephoram.getType(),
            sdf.parse(satelliteNephoram.getDateChar()), satelliteNephoram.getTimeChar()) + ".jpg";
            System.out.println(fileName);////////
            satelliteNephoram.setSateTitle(DbConfig.getYt3AFileName(satelliteNephoram.getType(),
                    sdf.parse(satelliteNephoram.getDateChar()), satelliteNephoram.getTimeChar()));
            String servicePath = urlpath + fileName;// 服务器路径
            System.out.println(servicePath);/////////
            File serviceFile = new File(servicePath);// 服务器文件
            if (serviceFile.exists()) {// 把文件上传到服务器
                if (operatingSystem.equals("Windows")) {
                    satelliteNephoram.setJwImgPath("Temp\\FY3H\\" +
                            "" + fileName);
                } else {
                    satelliteNephoram.setJwImgPath("Temp/FY3H/" +
                            "" + fileName);
                }

            } else {
//                Map<String, Object> map = new HashMap<String, Object>();
//                map.put("datayear", satelliteNephoram.getDataYear().toString());
//                map.put("datechar", satelliteNephoram.getDateChar());
//                map.put("yttype", satelliteNephoram.getType());
//                map.put("timechar", satelliteNephoram.getTimeChar());
//                map.put("collectionName", "image_file");
//                map.put("advCode", DbConfig.advCode);
//                byte[] data = ms.selectData(map);
                String datayear = satelliteNephoram.getDataYear().toString();
                String datechar = satelliteNephoram.getDateChar();
                String yttype = satelliteNephoram.getType();
                String timechar = satelliteNephoram.getTimeChar();
                String collectionName = "image_file";
                String filePath = "D:\\Desktop\\file\\test.png";
                byte[] data = FileUtil.fileToBytes(filePath);
                if (data == null) {
                    satelliteNephoram.setLbImgPath("");
                } else {
                    FileUtil.bytesToFile(data, servicePath);
                    if (operatingSystem.equals("Windows")) {
                        satelliteNephoram.setJwImgPath("Temp\\FY3H\\" + fileName);
                    } else {
                        satelliteNephoram.setJwImgPath("Temp/FY3H/" + fileName);
                    }

                }
            }
        }
        return resultList;
    }


    /* 获得风云三号云图 */
    @RequestMapping("/getFsPoint")
    @ResponseBody
    public Object getFsPoint(HttpServletRequest request, Model model) throws Exception {
        String coords = request.getParameter("coords");// 坐标
        String result = "[";
        String[] coors = coords.split(";");
        for (int i = 0; i < coors.length; i++) {
            result += "{";
            result += "\"lon\":" + coors[i].split(",")[0] + ",";
            result += "\"lat\":" + coors[i].split(",")[1] + "";
            result += "},";
        }
        if (result.endsWith(",")) {
            result = result.substring(0, result.length() - 1);
        }
        result = result + "]";
        return result;
    }

    // txt查看
    @RequestMapping("/ReadTxt")
    @ResponseBody
    public String ReadTxt(HttpServletRequest request) throws Exception {
        String dateyear = request.getParameter("dateyear");//
        String datechar = request.getParameter("datechar");//
        String yttype = request.getParameter("yttype");//
        String timechar = request.getParameter("timechar");//
        String urlpath;
        if (operatingSystem.equals("Windows")) {
            urlpath = request.getSession().getServletContext().getRealPath("/") + "Temp\\FireTxt\\";// 临时文件目录
        } else {
            urlpath = request.getSession().getServletContext().getRealPath("/") + "Temp/FireTxt/";// 临时文件目录
        }


        FileUtil.mkDirs(urlpath);// 创建文件夹，生成多级目录
        FileUtil.ClearTempFiles(urlpath, 1000);// 清除缓存
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String fileName = DbConfig.getYtFileName(yttype, sdf.parse(datechar), timechar) + ".txt";// 文件名
        String result = "";// 服务器文件
        String txtPath = urlpath + fileName;
        File txtFile = new File(txtPath);
        if (txtFile.exists()) {
            result = FileUtil.readLogByStringAndEncode(txtPath, "GB2312");
        } else {
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("datayear", dateyear);
            map.put("datechar", datechar);
            map.put("yttype", yttype);
            map.put("timechar", timechar);
            map.put("collectionName", "txt_file");
            map.put("advCode", DbConfig.advCode);
            byte[] data = ms.selectData(map);
            FileUtil.bytesToFile(data, txtPath);
            // 下载doc文件
            if (data == null) {
                return "";
            }
            result = FileUtil.readLogByStringAndEncode(txtPath, "GB2312");
        }
        return result;
    }

    /* 初始化火险预警界面 */
    @RequestMapping("/initFirePage")
    @ResponseBody
    public Object initFirePage() {
        ArrayList<Object> arrayList = new ArrayList<Object>();/* object各种类型数据 */
        HXYJ_Warning newestDate = forestryfcstService.getFireNewDate();
        // 加载列表
        DateTime datechar = new DateTime(newestDate.getDateChar());// DateTime类型
        String startDate = datechar.AddDays(-600).toDateStringf();// 开始时间
        String endDate = datechar.toDateStringf();// 结束时间
        arrayList.add(startDate);// 开始时间
        arrayList.add(endDate);// 结束时间
        return arrayList;
    }

    /* 得到火险预警信息 */
    @RequestMapping("/getFirewarning")
    @ResponseBody
    public Object getFirewarning(HttpServletRequest request, Model model) throws Exception {
        FireSearch selectKey = new FireSearch();// 查询类
        String startDate = request.getParameter("startDate") + ":00:00";// 开始时间
        String endDate = request.getParameter("endDate") + ":59:59";// 结束时间
        String type = request.getParameter("type");// 结束时间
        String time = "";
        String gradeArea3 = "";
        String gradeArea4 = "";
        String gradeArea5 = "";
        String docpath = "";
        Integer docid;
        selectKey.setStartDate(startDate);
        selectKey.setEndDate(endDate);
        selectKey.setType(type);
        DmMapPoint[] points = null;
        List<Warning> resultList = new ArrayList<Warning>();// 主
        List<HXYJ_Warning> warning = forestryfcstService.getFirewarning(selectKey); //
        int count = warning.toArray().length;
        for (int i = 0; i < count; i++) {
            if (warning.get(i).getGradeArea2() != null && !warning.get(i).getGradeArea2().equals("")) {
                warning.get(i).setWarntype("蓝色预警");
            }
            if (warning.get(i).getGradeArea3() != null && !warning.get(i).getGradeArea3().equals("")) {
                warning.get(i).setWarntype("黄色预警");
            }
            if (warning.get(i).getGradeArea4() != null && !warning.get(i).getGradeArea4().equals("")) {
                warning.get(i).setWarntype("橙色预警");
            }
            if (warning.get(i).getGradeArea5() != null && !warning.get(i).getGradeArea5().equals("")) {
                warning.get(i).setWarntype("红色预警");
            }
            ArrayList<Entites> entites = new ArrayList<Entites>();

            time = warning.get(i).getDateChar().toString();
            Date date = new SimpleDateFormat("EEE MMM dd HH:mm:ss Z yyyy", Locale.UK).parse(time);
            // 格式化
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            String sDate = sdf.format(date);// 时间
            docid = warning.get(i).getDocid();
            gradeArea3 = warning.get(i).getGradeArea3();// 黄色区域
            gradeArea4 = warning.get(i).getGradeArea4();// 橙色区域
            gradeArea5 = warning.get(i).getGradeArea5();// 红色区域
            docpath = warning.get(i).getDocpath();// 文档位置
            String[] posArr = warning.get(i).getPos().split("\\*");// 三个部分，*分隔
            for (String pos : posArr) {
                try {
                    if (pos == null || pos.equals("")) {
                        continue;
                    }
                    Entites entity = new Entites();// 实体类：颜色，坐标
                    ArrayList<MyPoint> tempPos = new ArrayList<MyPoint>();// 临时
                    String strColor = pos.split("#")[0];// #分隔，第一个代表颜色
                    entity.setColor(strColor);// 存入类
                    String[] dotset = pos.split("#")[1].split(",");// 坐标数组
                    points = new DmMapPoint[dotset.length];
                    Integer index = 0;
                    for (String strDot : dotset) {
                        String[] dot = strDot.split(" ");
                        // DmMapPoint dmDot = new DmMapPoint(Double.parseDouble(dot[0]), Double.parseDouble(dot[1]));
                        // DmMapPoint ltDot = transformService.LambertConvertToLonLat(dmDot.x, dmDot.y);
                        points[index] = new DmMapPoint(Double.parseDouble(dot[0]), Double.parseDouble(dot[1]));
                        index++;
                    }
                    MapCommon dmMapCom = new MapCommon();
                    int[] parts = new int[1];
                    parts[0] = points.length;
                    entity.setPosArr(tempPos);
                    entites.add(entity);
                } catch (Exception e) {
                    System.err.println(e.getStackTrace());
                }
            }
            Warning nwarning = new Warning();// 总
            nwarning.setGradeArea3(gradeArea3);
            nwarning.setGradeArea4(gradeArea4);
            nwarning.setGradeArea5(gradeArea5);
            nwarning.setWarntype(warning.get(i).getWarntype());
            nwarning.setDocpath(docpath);
            nwarning.setDateChar(sDate);
            nwarning.setDocid(docid);
            nwarning.setEntites(entites);
            nwarning.setDpart(points);
            nwarning.setPos(warning.get(i).getPos());
            resultList.add(nwarning);
        }
        return resultList;
    }

    /* 面实体排序 */
    class SortByColor implements Comparator<Object> {
        public int compare(Object o1, Object o2) {
            // TODO Auto-generated method stub
            Entites entity1 = (Entites) o1;
            Entites entity2 = (Entites) o2;
            if (Integer.parseInt(entity1.getColor()) > Integer.parseInt(entity2.getColor()))
                return -1;
            return 1;
        }
    }

    /* 得到山洪预警文档 */
    @RequestMapping("/getWarningDoc")
    @ResponseBody
    public Object getWarningDoc( HttpServletRequest request ) throws ParseException, IOException {
        String docpath = request.getParameter("docpath");
        System.out.println(docpath);
        if (docpath == null || docpath.equals("")) {
            return "";
        }
        String id = forestryfcstService.getProductID(docpath);// 获取编号
        String urlpath;
        if (operatingSystem.equals("Windows")) {
            urlpath = request.getSession().getServletContext().getRealPath("/") + "Temp\\Fire\\";// 临时文件目录
        } else {
            urlpath = request.getSession().getServletContext().getRealPath("/") + "Temp/Fire/";// 临时文件目录
        }
        String path = request.getContextPath();
        String basePath = DbConfig.IP + path;
        FileUtil.mkDirs(urlpath);// 创建文件夹，生成多级目录
        FileUtil.ClearTempFiles(urlpath, 1000);// 清除缓存

        String fileName = docpath.split("\\\\")[docpath.split("\\\\").length - 1];// 文件名
        String doctype = fileName.split("\\.")[fileName.split("\\.").length - 1];// 文件类型
        String servicePath = "";// 服务器文件
        if (doctype.contains("doc")) {
            String pdfPath = urlpath + fileName.replace(doctype, "pdf");
            File pdfFile = new File(pdfPath);
            if (pdfFile.exists()) {
                if (operatingSystem.equals("Windows")) {
                    servicePath = "\\Temp\\Fire\\" + fileName.replace(doctype, "pdf");
                } else {
                    servicePath = "/Temp/Fire/" + fileName.replace(doctype, "pdf");
                }
                servicePath = basePath+servicePath;
            } else {
                Map<String, Object> map = new HashMap<String, Object>();
                map.put("id", id);
                map.put("table_name", "base_product");
                map.put("collectionName", "pdf_file");
                map.put("advCode", DbConfig.advCode);
                byte[] data = ms.selectData(map);

                // 下载doc文件
                if (data == null) {
                    return "";
                }
                FileUtil.bytesToFile(data, pdfPath);
                if (operatingSystem.equals("Windows")) {
                    servicePath = "\\Temp\\Fire\\" + fileName.replace(doctype, "pdf");
                } else {
                    servicePath = "/Temp/Fire/" + fileName.replace(doctype, "pdf");
                }

                servicePath = basePath + servicePath;
            }
        }
        servicePath = servicePath.replace("\\", "/");
        return servicePath;
    }

    /* 得到病虫害信息 */
    @RequestMapping("/initInsectpests")
    @ResponseBody
    public Object initInsectpests(HttpServletRequest request, Model model) {
        List<Insectpests> resultList = forestryfcstService.initInsectpests(); //

        return resultList;
    }

    /* 得到病虫害信息 */
    @RequestMapping("/getInsectpests")
    @ResponseBody
    public Object getInsectpests(HttpServletRequest request, Model model) {
        InsectSearch selectKey = new InsectSearch();// 查询类
        String zbnames = request.getParameter("type");
        String disaster = request.getParameter("disaster");
        selectKey.setZbnames(zbnames);
        selectKey.setDisaster(disaster);
        List<Insectpests> resultList = forestryfcstService.getInsectpests(selectKey); //

        return resultList;
    }

    /* 得到病虫害预报信息 */
    @RequestMapping("/getYBInsectpests")
    @ResponseBody
    public Object getYBInsectpests(HttpServletRequest request, Model model) throws Exception {
        InsectSearch selectKey = new InsectSearch();// 查询类
        String zbnames = request.getParameter("type");
        String disaster = request.getParameter("disaster");
        String date = request.getParameter("date");
        selectKey.setZbnames(zbnames);
        selectKey.setDisaster(disaster);
        selectKey.setDate(date);
        List<Insectpests> resultList = forestryfcstService.getInsectpests(selectKey); //
        List<Insectpests> result = new ArrayList<Insectpests>();
        String servicePath = "";// 服务器文件
        String path = request.getContextPath();
        String basePath = DbConfig.IP + path;
        for (Insectpests pests : resultList) {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            DateTime Sdttime = new DateTime();
            DateTime Edttime = new DateTime();
            if (!StringUtil.IsNullOrEmpty(pests.getEasyhappentime())) {
                String strtemp = pests.getEasyhappentime().replace("月", "");
                String[] strItems = strtemp.split("-");
                String strDate = "";
                if (strItems.length > 1) {
                    strDate = DateTime.now().GetYear() + "-" + strItems[0] + "-" + "01";
                    Sdttime = new DateTime(sdf.parse(strDate));
                    strDate = DateTime.now().GetYear() + "-" + strItems[1] + "-" + "01";
                    Edttime = new DateTime(sdf.parse(strDate));
                    Edttime = Edttime.AddMonths(1).AddDays(-1);
                    if (Edttime.before(Sdttime)) {
                        Edttime = Edttime.AddYears(1);
                    }
                }
                servicePath=basePath+servicePath;
            } else {
                if (!StringUtil.IsNullOrEmpty(pests.getStarttime()) && !StringUtil.IsNullOrEmpty(pests.getEndtime())) {
                    String strDate = "";
                    strDate = DateTime.now().GetYear() + "-" + pests.getStarttime();
                    Sdttime = new DateTime(sdf.parse(strDate));
                    strDate = DateTime.now().GetYear() + "-" + pests.getEndtime().substring(5, 7) + "-"
                            + pests.getEndtime().substring(8, 10);
                    Edttime = new DateTime(sdf.parse(strDate));
                    if (Edttime.before(Sdttime)) {
                        Edttime = Edttime.AddYears(1);
                    }
                }
            }
            String[] strCountys = pests.getCounty().toString().trim().split(",");

            boolean NoWonditions = false;
            if (new DateTime(sdf.parse(date)).after(Sdttime) && new DateTime(sdf.parse(date)).before(Edttime)
                    && pests.getMintemp() == null && pests.getMaxtemp() == null && pests.getMinrain() == null
                    && pests.getMaxrain() == null && pests.getSunhour() == null) {
                NoWonditions = true;
            }
            Insectpests pst = new Insectpests();
            pst = forestryfcstService.getYBInsectpests(strCountys, pests, (new DateTime(sdf.parse(date))),
                    NoWonditions);
            if (pst.getPlantname() != null) {
                result.add(pst);
            }
        }
        return result;
    }

    /* 得到历史火点 */
    @RequestMapping("/getFirePoint")
    @ResponseBody
    public Object getFirePoint(HttpServletRequest request, Model model) throws Exception {
        FirePointSearch selectKey = new FirePointSearch();// 查询类
        String FireName = request.getParameter("FireName");
        String Address = request.getParameter("Address");
        String StationName = request.getParameter("StationName");
        String DisasterArea = request.getParameter("DisasterArea");
        String DisasterAreaTo = request.getParameter("DisasterAreaTo");
        String PopThreat = request.getParameter("PopThreat");
        String PopThreatTo = request.getParameter("PopThreatTo");
        String PropertyThreat = request.getParameter("PropertyThreat");
        String PropertyThreatTo = request.getParameter("PropertyThreatTo");
        selectKey.setFirename(FireName);
        selectKey.setAddress(Address);
        selectKey.setStationname(StationName);
        selectKey.setDisasterarea(DisasterArea);
        selectKey.setDisasterareato(DisasterAreaTo);
        selectKey.setPopthreat(PopThreat);
        selectKey.setPopthreatto(PopThreatTo);
        selectKey.setPropertythreat(PropertyThreat);
        selectKey.setPropertythreatto(PropertyThreatTo);
        List<FirePoint> resultList = forestryfcstService.getFirePoint(selectKey); //

        return resultList;
    }

    /* 初始化专题服务界面 */
    @RequestMapping("/initSpeServicePage")
    @ResponseBody
    public Object initSpeServicePage() {
        base_product newestDate = forestryfcstService.getSpeServiceNewDate();
        // 加载列表
        String date = DateTime.now().toDateString();
        if (newestDate.getForecasttime() != null) {
            DateTime datechar = new DateTime(newestDate.getForecasttime());// DateTime类型
            date = datechar.toDateString();// 开始时间
        }
        return date;
    }

    /* 得到专题服务文档 */
    @RequestMapping("/getServiceDoc")
    @ResponseBody
    public Object getServiceDoc(HttpServletRequest request, Model model) throws ParseException {
        String date = request.getParameter("date");// 获取日期

        List<base_product> resultList = forestryfcstService.getServiceDoc(date);
        String id = "";
        String docpath = "";
        if (resultList != null && resultList.size() > 0) {
            id = resultList.get(0).getId().toString();
            docpath = resultList.get(0).getProductname();
        }
        String urlpath;
        String path = request.getContextPath();
        String basePath = DbConfig.IP + path;
        String servicePath = "";// 服务器文件

        if (operatingSystem.equals("Windows")) {
            urlpath = request.getSession().getServletContext().getRealPath("/") + "Temp\\Service\\";// 临时文件目录
        } else {
            urlpath = request.getSession().getServletContext().getRealPath("/") + "Temp/Service/";// 临时文件目录
        }
                servicePath=basePath+servicePath;
        FileUtil.mkDirs(urlpath);// 创建文件夹，生成多级目录
        FileUtil.ClearTempFiles(urlpath, 1000);// 清除缓存

        String fileName = docpath.split("\\\\")[docpath.split("\\\\").length - 1];// 文件名
        String doctype = fileName.split("\\.")[fileName.split("\\.").length - 1];// 文件类型
        if (doctype.contains("doc")) {
            String localPath = urlpath + fileName;
            String pdfPath = urlpath + fileName.replace(doctype, "pdf");
            File pdfFile = new File(pdfPath);
            if (pdfFile.exists()) {
                if (operatingSystem.equals("Windows")) {
                    servicePath = "Temp\\Service\\" + fileName.replace(doctype, "pdf");
                } else {
                    servicePath = "Temp/Service/" + fileName.replace(doctype, "pdf");
                }

            } else {
                Map<String, Object> map = new HashMap<String, Object>();
                map.put("id", id);
                map.put("table_name", "base_product");
                map.put("collectionName", "pdf_file");
                map.put("advCode", DbConfig.advCode);
                byte[] data = ms.selectData(map);
                // 下载doc文件
                if (data == null) {
                    return "";
                }
                FileUtil.bytesToFile(data, pdfPath);
                File localFile = new File(pdfPath);// 本地文件
                if (localFile.exists()) {
                    try {
                        if (operatingSystem.equals("Windows")) {
                            servicePath = "Temp\\Service\\" + fileName.replace(doctype, "pdf");
                        } else {
                            servicePath = "Temp/Service/" + fileName.replace(doctype, "pdf");
                        }

                    } catch (Exception e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
            }
        }
        servicePath = servicePath.replace("\\", "/");
        return servicePath;
    }

    /* 预警区内实况信息 */
    @RequestMapping("/getSKinfo")
    @ResponseBody
    public Object getSKinfo(HttpServletRequest request, Model model) throws Exception {
        String startDate = request.getParameter("startDate") + ":00:00";// 开始时间
        String endDate = request.getParameter("endDate") + ":59:59";// 结束时间
        String poss = request.getParameter("pos");// 坐标
        String[] posArr = poss.split("\\*");// 三个部分，*分隔
        List<DmMapPoint> lonlat = new ArrayList<DmMapPoint>();
        List<String> stationids = new ArrayList<String>();
        String skstations = "";
        for (String pos : posArr) {
            try {
                if (pos == null || pos.equals("")) {
                    continue;
                }
                String[] dotset = pos.split("#")[1].split(",");// 坐标数组
                DmMapPoint[] points = new DmMapPoint[dotset.length];
                DmMapPoint[] point = new DmMapPoint[dotset.length];
                Integer index = 0;
                for (String strDot : dotset) {
                    String[] dot = strDot.split(" ");
                    DmMapPoint dmDot = new DmMapPoint(Double.parseDouble(dot[0]), Double.parseDouble(dot[1]));
                    point[index] = transformService.LambertConvertToLonLat(Double.parseDouble(dot[0]), Double.parseDouble(dot[1]));
                    points[index] = dmDot;
                    index++;
                }
                DmMapRectangle rct = new DmMapRectangle();
                MapCommon dmMapCom = new MapCommon();
                int[] parts = new int[1];
                parts[0] = points.length;
                DmMapRectangle rect = dmMapCom.getObjRect(Arrays.asList(point));
                //截取面
                DmMapPoint dmDotLb1 = transformService.LambertConvertToLonLat(rect.minX, rect.minY);
                DmMapPoint dmDotLb2 = transformService.LambertConvertToLonLat(rect.maxX, rect.maxY);
                rect.minX = dmDotLb1.x;
                rect.minY = dmDotLb1.y;
                rect.maxX = dmDotLb2.x;
                rect.maxY = dmDotLb2.y;
                List<smallscale_station> stations = qxInfoService.getStations(rect);
                for (smallscale_station city : stations) {
                    DmMapPoint dmDotJW = new DmMapPoint(city.getLongitude(), city.getLatitude());
                    DmMapPoint dmDotLb = transformService.LonLatConvertToLambert(dmDotJW.x, dmDotJW.y);
                    //判断点是否在面内
                    if (dmMapCom.pointWithinPolygon(Arrays.asList(points), dmDotLb.x, dmDotLb.y)) {
                        if (!skstations.contains(city.getStationid())) {
                            skstations += city.getStationid() + ",";
                            lonlat.add(dmDotJW);
                            stationids.add(city.getStationid());
                        }
                    }
                }
            } catch (Exception e) {
                System.err.println(e.getStackTrace());
            }
        }
        List<MediumSmallScale> resultList = new ArrayList<MediumSmallScale>();
        List<msgmediumsmallscale> dataList = new ArrayList<>();
        if (stationids.size() > 0) {
            dataList = qxInfoService.getSKinfo(startDate, endDate, stationids);
        }
        //获取实时站点信息
        for (msgmediumsmallscale msg : dataList) {
            MediumSmallScale smallscale = new MediumSmallScale();
            smallscale.setObservTime(msg.getObservtime());
            smallscale.setStationID(msg.getStationid());
            smallscale.setLongitude(msg.getLongitude());
            smallscale.setLatitude(msg.getLatitude());
            smallscale.setLon(msg.getLongitude());
            smallscale.setLat(msg.getLatitude());
            smallscale.setStationName(msg.getStationname());
            smallscale.setRain(Float.parseFloat(String.format("%.1f", msg.getRain())));
            smallscale.setDryBulbTemp(Float.parseFloat(String.format("%.1f", msg.getDrybulbtemp())));
            smallscale.setInstantWindV(Float.parseFloat(String.format("%.1f", msg.getInstantwindv())));
            smallscale.setRelHumidity(msg.getRelhumidity());
            smallscale.setPressureSea(Float.parseFloat(String.format("%.1f", msg.getStationpress())));
            smallscale.setCity(msg.getCity());
            smallscale.setCounty(msg.getCounty());
            DmMapPoint dmDot = new DmMapPoint(msg.getLongitude(), msg.getLatitude());
            DmMapPoint ltDot = transformService.LonLatConvertToLambert(dmDot.x, dmDot.y);
            smallscale.setX(ltDot.x);
            smallscale.setY(ltDot.y);
            resultList.add(smallscale);
        }
        return resultList;
    }

    /* 预警区内预报信息 */
    @RequestMapping("/getYBinfo")
    @ResponseBody
    public Object getYBinfo(HttpServletRequest request, Model model) throws Exception {
        String poss = request.getParameter("pos");// 坐标
        String[] posArr = poss.split("\\*");// 三个部分，*分隔
        List<DmMapPoint> lonlat = new ArrayList<DmMapPoint>();
        List<String> stationids = new ArrayList<String>();
        String ybstations = "";
        for (String pos : posArr) {
            try {
                if (pos == null || pos.equals("")) {
                    continue;
                }
                String[] dotset = pos.split("#")[1].split(",");// 坐标数组
                DmMapPoint[] points = new DmMapPoint[dotset.length];
                DmMapPoint[] point = new DmMapPoint[dotset.length];
                Integer index = 0;
                for (String strDot : dotset) {
                    String[] dot = strDot.split(" ");
                    DmMapPoint dmDot = new DmMapPoint(Double.parseDouble(dot[0]), Double.parseDouble(dot[1]));
                    point[index] = transformService.LambertConvertToLonLat(Double.parseDouble(dot[0]), Double.parseDouble(dot[1]));
                    points[index] = dmDot;
                    index++;
                }
                DmMapRectangle rct = new DmMapRectangle();
                MapCommon dmMapCom = new MapCommon();
                int[] parts = new int[1];
                parts[0] = points.length;
                DmMapRectangle rect = dmMapCom.getObjRect(Arrays.asList(point));
                DmMapPoint dmDotLb1 = transformService.LambertConvertToLonLat(rect.minX, rect.minY);
                DmMapPoint dmDotLb2 = transformService.LambertConvertToLonLat(rect.maxX, rect.maxY);
                rect.minX = dmDotLb1.x;
                rect.minY = dmDotLb1.y;
                rect.maxX = dmDotLb2.x;
                rect.maxY = dmDotLb2.y;
                //查询预报站点
                List<township_station> stations = qxInfoService.getYBStations(rect);
                for (township_station city : stations) {
                    DmMapPoint dmDotJW = new DmMapPoint(city.getLongitude(), city.getLatitude());
                    DmMapPoint dmDotLb = transformService.LonLatConvertToLambert(dmDotJW.x, dmDotJW.y);
                    //判断预报站点是否在预警区内
                    if (dmMapCom.pointWithinPolygon(Arrays.asList(points), dmDotLb.x, dmDotLb.y)) {
                        if (!ybstations.contains(city.getStationid())) {
                            ybstations += city.getStationid() + ",";
                            lonlat.add(dmDotJW);
                            stationids.add(city.getStationid());
                        }
                    }
                }
            } catch (Exception e) {
                System.err.println(e.getStackTrace());
            }
        }
        List<CityFcstInfo> resultList = new ArrayList<CityFcstInfo>();
        List<township_forecasttemp> fcstList = new ArrayList<township_forecasttemp>();
        if (stationids.size() > 0) {
            fcstList = qxInfoService.getYBinfo(stationids);
        }
        int count = fcstList.toArray().length;
        if (count > 0) {
            WebCtrlData wcd = new WebCtrlData();
            for (int i = 0; i < count; i += 2) {
                String strStationID = fcstList.get(i).getStationid();
                String strCountyName = fcstList.get(i).getStationname();
                if (strCountyName.contains("乡")) {
                    strCountyName = strCountyName.substring(0, strCountyName.indexOf('乡') + 1);
                }
                if (strCountyName.contains("镇")) {
                    strCountyName = strCountyName.substring(0, strCountyName.indexOf('镇') + 1);
                }
                String weather = "";// 天气信息
                String windD = "";// 风向信息
                String windV = "";// 风速信息
                String windS = "";// 风速信息
                String windD12 = wcd.GetAllFx(fcstList.get(i).getWindd().toString().replace("-65535", "0").trim());
                String windD24 = wcd.GetAllFx(fcstList.get(i + 1).getWindd().toString().replace("-65535", "0").trim());
                String windV12 = wcd.GetWeatherFs(String.valueOf(WebCtrlData.FengSuToFengJi(fcstList.get(i).getWinds())));
                String windV24 = wcd.GetWeatherFs(String.valueOf(WebCtrlData.FengSuToFengJi(fcstList.get(i + 1).getWinds())));
                String windS12 = String.valueOf(fcstList.get(i).getWinds());
                String windS24 = String.valueOf(fcstList.get(i + 1).getWinds());
                if (windD12.equals(windD24)) {
                    windD += windD12;
                } else {
                    windD += windD12 + "转" + windD24;
                }
                if (windV12.equals(windV24)) {
                    windV += windV12;
                } else {
                    windV += windV12 + "~" + windV24;
                }
                if (windS12.equals(windS24)) {
                    windS += windS12 + "m/s";
                } else {
                    windS += windS12 + "~" + windS24 + "m/s";
                }
                if (fcstList.get(i).getWeather1().trim().equals(fcstList.get(i + 1).getWeather1().trim())) {
                    weather += fcstList.get(i).getWeather1().trim();
                } else {
                    weather += fcstList.get(i).getWeather1().trim() + "转" + fcstList.get(i + 1).getWeather1().trim();
                }
                double maxTemp = fcstList.get(i).getMaxtemp() > fcstList.get(i + 1).getMaxtemp()
                        ? fcstList.get(i).getMaxtemp() : fcstList.get(i + 1).getMaxtemp();
                double minTemp = fcstList.get(i).getMintemp() > fcstList.get(i + 1).getMintemp()
                        ? fcstList.get(i + 1).getMintemp() : fcstList.get(i).getMintemp();
                String pic1 = String.format("%02d",
                        Integer.parseInt(WebCtrlData.WeatherNameToPicPath(fcstList.get(i).getWeather1())));
                String pic2 = String.format("%02d",
                        Integer.parseInt(WebCtrlData.WeatherNameToPicPath(fcstList.get(i + 1).getWeather1())));
                CityFcstInfo fcstInfo = new CityFcstInfo();
                fcstInfo.setStationId(strStationID);
                fcstInfo.setStationName(strCountyName);
                fcstInfo.setMinTemp(minTemp);
                fcstInfo.setMaxTemp(maxTemp);
                fcstInfo.setRain(fcstList.get(i).getRain());
                fcstInfo.setWindD(windD);
                fcstInfo.setWindV(windV);
                fcstInfo.setWindS(windS);
                fcstInfo.setPic1(pic1);
                fcstInfo.setPic2(pic2);
                fcstInfo.setLat(fcstList.get(i).getLatitude());
                fcstInfo.setLon(fcstList.get(i).getLongitude());
                DmMapPoint dt = transformService.LonLatConvertToLambert(fcstInfo.getLon(), fcstInfo.getLat());
                fcstInfo.setX(dt.x);
                fcstInfo.setY(dt.y);
                fcstInfo.setWeather1(fcstList.get(i).getWeather1().trim());
                fcstInfo.setWeather2(fcstList.get(i + 1).getWeather1().trim());
                fcstInfo.setWeather(weather);
                fcstInfo.setHumid(String.valueOf(fcstList.get(i).getHumid()) + "%");
                resultList.add(fcstInfo);
            }
        }
        return resultList;
    }

    /* 地理分析 */
    @RequestMapping("/getAnalysis")
    @ResponseBody
    public Object getAnalysis(HttpServletRequest request, Model model) throws Exception {
        String analysis = request.getParameter("analysis");// 分析图层
        String result = "[";
        if (analysis.contains("历史火灾点")) {
            FirePointSearch selectKey = new FirePointSearch();// 查询类
            List<FirePoint> resultList = forestryfcstService.getFirePoint(selectKey);
            String poss = request.getParameter("pos");// 坐标
            String[] posArr = poss.split("\\*");// 三个部分，*分隔
            for (String pos : posArr) {
                try {
                    if (pos == null || pos.equals("")) {
                        continue;
                    }
                    String[] dotset = pos.split("#")[1].split(",");// 坐标数组
                    DmMapPoint[] points = new DmMapPoint[dotset.length];
                    Integer index = 0;
                    for (String strDot : dotset) {
                        String[] dot = strDot.split(" ");
                        DmMapPoint dmDot = new DmMapPoint(Double.parseDouble(dot[0]), Double.parseDouble(dot[1]));
                        points[index] = dmDot;
                        index++;
                    }
                    MapCommon dmMapCom = new MapCommon();
                    int[] parts = new int[1];
                    parts[0] = points.length;
                    for (FirePoint city : resultList) {
                        DmMapPoint dmDotJW = new DmMapPoint(city.getLon(), city.getLat());
                        DmMapPoint dmDotLb = transformService.LonLatConvertToLambert(dmDotJW.x, dmDotJW.y);
                        //判断历史火灾点是否在预警区内
                        if (dmMapCom.pointWithinPolygon(Arrays.asList(points), dmDotLb.x, dmDotLb.y)) {
                            //判断点是否在多边形内
                            result += "{";
                            result += "\"id\":\"" + city.getId() + "\",";
                            result += "\"firename\":\"" + city.getFirename() + "\",";
                            result += "\"address\":\"" + city.getAddress() + "\",";
                            result += "\"stationName\":\"" + city.getStationName() + "\",";
                            result += "\"announcedtime\":\"" + city.getAnnouncedtime() + "\",";
                            result += "\"disasterarea\":\"" + city.getDisasterarea() + "\",";
                            result += "\"popthreat\":\"" + city.getPopthreat() + "\",";
                            result += "\"propertythreat\":\"" + city.getPropertythreat() + "\",";
                            result += "\"lon\":" + city.getLon() + ",";
                            result += "\"lat\":" + city.getLat() + "";
                            result += "},";
                        }
                    }
                } catch (Exception e) {
                    System.err.println(e.getStackTrace());
                }
            }
        } else if (analysis.contains("村点")) {
            String poss = request.getParameter("pos");// 坐标
            String[] posArr = poss.split("\\*");// 三个部分，*分隔
            for (String pos : posArr) {
                try {
                    if (pos == null || pos.equals("")) {
                        continue;
                    }
                    String[] dotset = pos.split("#")[1].split(",");// 坐标数组
                    DmMapPoint[] points = new DmMapPoint[dotset.length];
                    DmMapPoint[] point = new DmMapPoint[dotset.length];
                    Integer index = 0;
                    for (String strDot : dotset) {
                        String[] dot = strDot.split(" ");
                        DmMapPoint dmDot = new DmMapPoint(Double.parseDouble(dot[0]), Double.parseDouble(dot[1]));
                        point[index] = transformService.LambertConvertToLonLat(Double.parseDouble(dot[0]), Double.parseDouble(dot[1]));
                        points[index] = dmDot;
                        index++;
                    }
                    MapCommon dmMapCom = new MapCommon();
                    int[] parts = new int[1];
                    parts[0] = points.length;
                    DmMapRectangle rect = dmMapCom.getObjRect(Arrays.asList(point));
                    DmMapPoint dmDotLb1 = new DmMapPoint(rect.minX, rect.minY);
                    DmMapPoint dmDotLb2 = new DmMapPoint(rect.maxX, rect.maxY);
                    rect.minX = dmDotLb1.x;
                    rect.minY = dmDotLb1.y;
                    rect.maxX = dmDotLb2.x;
                    rect.maxY = dmDotLb2.y;
                    List<village> resultList = qxInfoService.getCountryPoint(rect);
                    for (village city : resultList) {
                        DmMapPoint dmDotJW = new DmMapPoint(city.getLon(), city.getLat());
                        DmMapPoint dmDotLb = transformService.LonLatConvertToLambert(dmDotJW.x, dmDotJW.y);
                        //判断是否在预警区内
                        if (dmMapCom.pointWithinPolygon(Arrays.asList(points), dmDotLb.x, dmDotLb.y)) {
                            result += "{";
                            result += "\"dmgisId\":\"" + city.getId() + "\",";
                            result += "\"stationName\":\"" + city.getVillagename() + "\",";
                            result += "\"population\":\"" + city.getPopulation() + "\",";
                            result += "\"mayor\":\"" + city.getVillagehead() + "\",";
                            result += "\"tel\":\"" + city.getContacttel() + "\",";
                            result += "\"lon\":" + city.getLon() + ",";
                            result += "\"lat\":" + city.getLat() + ",";
                            result += "\"county\":\"" + city.getCountry() + "\"";
                            result += "},";
                        }
                    }
                } catch (Exception e) {
                    System.err.println(e.getStackTrace());
                }
            }
        }
        if (result.endsWith(",")) {
            result = result.substring(0, result.length() - 1);
        }
        result = result + "]";
        return result;
    }

    @RequestMapping("/getHXAreaDoc")
    @ResponseBody
    public Object getHXAreaDoc(HttpServletRequest request, Model model) throws Exception {
        String docid = request.getParameter("docid");
        List<DZWarning> result = forestryfcstService.getDZAreaDoc(docid);
        // 兰伯特转经纬度
        for (DZWarning dzWarning : result) {
            if (dzWarning.getGradeArea2() != null && !dzWarning.getGradeArea2().equals("")) {
                dzWarning.setWarLevel("蓝色预警");
            }
            if (dzWarning.getGradeArea3() != null && !dzWarning.getGradeArea3().equals("")) {
                dzWarning.setWarLevel("黄色预警");
            }
            if (dzWarning.getGradeArea4() != null && !dzWarning.getGradeArea4().equals("")) {
                dzWarning.setWarLevel("橙色预警");
            }
            if (dzWarning.getGradeArea5() != null && !dzWarning.getGradeArea5().equals("")) {
                dzWarning.setWarLevel("红色预警");
            }
            ArrayList<CEntity> cEntities = new ArrayList<CEntity>();
            if (!StringUtil.IsNullOrEmpty(dzWarning.getPos())) {
                String[] posArr = dzWarning.getPos().split("\\*");
                for (String pos : posArr) {
                    try {
                        if (pos == null || pos.equals("")) {
                            continue;
                        }
                        CEntity cEntity = new CEntity();
                        ArrayList<MyPoint> tempPos = new ArrayList<MyPoint>();
                        String strColor = pos.split("#")[0];
                        // 16进制颜色
                        cEntity.setColor(strColor);
                        String[] dotset = pos.split("#")[1].split(",");
                        int ii = 0;
                        for (String strDot : dotset) {
                            String[] dot = strDot.split(" ");
                            DmMapPoint dmDot = new DmMapPoint(Double.parseDouble(dot[0]), Double.parseDouble(dot[1]));
                            DmMapPoint ltDot = transformService.LambertConvertToLonLat(dmDot.x, dmDot.y);
                            MyPoint dm = new MyPoint(ltDot.x, ltDot.y);
                            tempPos.add(dm);
                            ii++;
                        }
                        cEntity.setPosArr(tempPos);
                        cEntities.add(cEntity);
                    } catch (Exception e) {
                        System.err.println(e.getStackTrace());
                    }
                }
                dzWarning.setPos(dzWarning.getPos());
                dzWarning.setEntites(cEntities);
            }

            Date date = dzWarning.getDateChar();
            dzWarning.setDate(new DateTime(date).toDateString());
            dzWarning.setDateChar(null);
            // 文件处理

        }
        return result;
    }


    /* 得到火险预警文档描述 */
    @RequestMapping("/getHXWarning")
    @ResponseBody
    public Object getHXWarning(HttpServletRequest request, Model model) throws Exception {
        List<hxyj_warning> resultList = forestryfcstService.getHXWarning(); //
        String result = "";
        if (resultList != null && resultList.size() > 0) {
            if (!StringUtil.IsNullOrEmpty(resultList.get(0).getWarn_result()))
                result = new DateTime(resultList.get(0).getDatechar()).toDateTimeString() + "：" + resultList.get(0).getWarn_result();
            else
                result = new DateTime(resultList.get(0).getDatechar()).toDateTimeString() + "：暂无相关预警区描述!";
        }
        return result;
    }
}
